#include "icontool.h"
#include <QDebug>
#include <QGuiApplication>
#include <QClipboard>

IconTool::IconTool(QObject *parent)
    : QObject{parent}
{}

QPixmap IconTool::load_pixmap()
{
    return QPixmap::fromImage(load_img());
}

QImage IconTool::load_img()
{
    if(img_.isNull())
    {
       auto ret = img_.load("C:/Users/89351/Desktop/猫爪.png");

        qDebug() << "load image ret:" << ret;
    }

    return img_;
}

QUrl IconTool::render_svg(const QByteArray &svg)
{
    if(!svg_renderer_.load(svg)) {
        return QUrl("");
    }

    QPixmap pixmap(svg_renderer_.defaultSize());
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setBrush(QColor(255,11,11));
    svg_renderer_.render(&painter);
    painter.end();

    ImageProvider::instance().insertPixmap(std::move(pixmap));

    return QUrl(QString("image://icontool/%1").arg(img_id_++));
}

bool IconTool::save_icon()
{
    QImage img = ImageProvider::instance().getImage();
    img.scaled(32, 32).save("icon_32x32.ico");
    img.scaled(64, 64).save("icon_64x64.ico");
    return true;
}

QUrl IconTool::load_clipboard()
{
    auto clipboard = QGuiApplication::clipboard();

    QImage img = clipboard->image();
    if(!img.isNull()) {
        ImageProvider::instance().insertPixmap(QPixmap::fromImage(img));
        return QUrl(QString("image://icontool/%1").arg(img_id_++));

    }

    QString text = clipboard->text();
    if(!text.isEmpty()) {
        return render_svg(text.toUtf8());
    }

    return QUrl("");
}

QUrl IconTool::load_from_file(const QUrl &url)
{
    qDebug() << "url:" << url;

    if(!url.isLocalFile()) {
        return QUrl("");
    }

    QString filename = url.toLocalFile();
    if(filename.endsWith("svg")) {
        if(!svg_renderer_.load(filename)) {
            return QUrl("");
        }
        QPixmap pixmap(svg_renderer_.defaultSize());
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);
        painter.setBrush(QColor(255,11,11));
        svg_renderer_.render(&painter);
        painter.end();
        ImageProvider::instance().insertPixmap(std::move(pixmap));
    }
    else {
        QImage img;
        if(!img.load(filename)) {
            return QUrl("");
        }
        ImageProvider::instance().insertPixmap(QPixmap::fromImage(img));
    }

    return QUrl(QString("image://icontool/%1").arg(img_id_++));
}
